﻿@using System.Web.Script.Serialization
@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@Html.Partial("_ProductInfo_CreateOrEdit")


<input type="button" value="Create" data-bind="click:SaveProductInfo"/>

@{
    var model = ViewBag.Model;

    var jsonStr = new HtmlString(new JavaScriptSerializer().Serialize(model));
}

@section scripts{
    


<script>
    var init = @jsonStr;


    

    function ProductModel() {
        var self = this;
        self.Id = ko.observable(init.Id);
        self.ProductName = ko.observable(init.ProductName).extend({ 
            required: true,
            maxLength: 400
        });

        self.ShortDescription= ko.observable(init.ShortDescription);
        self.FullDescription= ko.observable(init.FullDescription);
        self.IsPublished = ko.observable(init.IsPublished);

        
        self.SaveProductInfo = function() {
            //alert(this.isValid());
            //alert(this.errors().length);
            if (this.isValid()) {
                $.ajax({
                    url: "/api/ProductApi/InsertProductInfo",
                    type: 'post',
                    data: ko.toJSON(self),
                    contentType: 'application/json',
                    success: function (result) {

                        if (result.Status == "0") {
                            alert("保存成功");
                            location.href = '/Product/Edit?productId=' + result.Id;
                        }
                        else {
                            alert("保存失败：" + result.Msg);
                        }
                    }
                });
            }

        
        };

    }

    var vm = new ProductModel();
    vm.errors = ko.validation.group(vm);
    ko.applyBindings(vm);
</script>

    }